<?php
require_once 'vlib/vlibTemplate.php';

/**
 * Library_Custom_View_Vlib - View class for vLib based templates.
 * 
 * @author  Eric Ritchie
 * @version 0.1
 */

class Library_Custom_View_Vlib extends Zend_View {
	/**
	 * vLib object to be populated with data. This will be used to finally render the page
	 * @var vlibTemplate
	 */
	public $vlib = null;
	
	/**
	 * The script path to the vLib template file. We need to define our
	 * own here, because the one in Zend_View is private.
	 * @var array
	 */
	private $_scriptPath = null;
	
	public function init() {
		$this->vlib = new vlibTemplate();
	}
	
	/**
	 * Sets the stack of view script paths.
	 *
	 * To clear all paths, use Zend_View_Excel::setScriptPath(null).
	 *
	 * @param string|array The directory (-ies) to set as the path.
	 * @return Zend_View_Abstract
	 */
	public function setScriptPath($path) {
		$this->_scriptPath = ( array ) $path;
		return $this;
	}
	
	/**
	 * Finds a view script from the available directories.
	 *
	 * @param $name string The base name of the script.
	 * @return void
	 */
	protected function _script($name) {
    if (0 == count($this->_scriptPath)) {
      require_once 'Zend/View/Exception.php';
      throw new Zend_View_Exception('no view script directory set; unable to determine location for view script', $this);
    }

    foreach ($this->_scriptPath as $dir) {
      if (is_readable($dir . $name)) {
        return $dir . $name;
      }
    }

    require_once 'Zend/View/Exception.php';
    $message = "script '$name' not found in path (".
                 implode(PATH_SEPARATOR, $this->_scriptPath).
                 ")";
    throw new Zend_View_Exception($message, $this);
  }
	
  /**
	 * Processes a view script and returns the output (or sends it to the browser
	 * in the case where we know the filename of the excel file).
	 *
	 * @param string $name The script script name to process.
	 * @return mixed The script output.
	 */
	public function render($name) {
		if (strpos($name, 'error.phtml') !== false) {
		  return parent::render($name);
		}
		
		$template = $this->_script($name);
		$this->vlib->newTemplate($template);
		
    ob_start();
    $this->vlib->pparse();

    return ob_get_clean();
	}
}